package com.lizk.study.netty.day009;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用直接内存映射的方式复制文件
 * @author lizhikui
 * @date 2019/7/7 9:40
 */
public class NioTest13 {
    public static void main(String[] args) throws IOException {

        //FileUtil.createFile("NioTest13-in.txt");
        File  file1 =  FileUtil.getFile("NioTest13-in.txt");
        File file2 = FileUtil.createFile("NioTest13-out.txt");


        RandomAccessFile inFile = new RandomAccessFile(file1,"rw");
        RandomAccessFile outFile = new RandomAccessFile(file2,"rw");

        FileChannel inFileChannel = inFile.getChannel();
        FileChannel outFileChannel = outFile.getChannel();


        int fileLength = (int) inFileChannel.size();
        MappedByteBuffer intBuffer = inFileChannel.map(FileChannel.MapMode.READ_WRITE, 0,fileLength);

        byte[] bytes = new byte [1024];
        intBuffer.get(bytes, 0, intBuffer.remaining());
        System.out.println(new String (bytes,0,fileLength));

        System.out.println("fileLength:"+ inFileChannel.size());

        MappedByteBuffer outBuffer = outFileChannel.map(FileChannel.MapMode.READ_WRITE, 0,  fileLength);
        outBuffer.put(bytes,0, fileLength);


        outBuffer.clear();


        inFileChannel.close();
        outFileChannel.close();
        inFile.close();
        outFile.close();


    }
}
